import React, { useEffect, useState } from 'react';
import { Card, Button, Modal, Toast } from 'antd-mobile';
import axios from '../api/axios';
import { endpoints } from '../api/endpoints';
import ModalImage from 'react-modal-image'; // 新增导入
import { getUserId } from '../utils/storage'; // 导入 getUserId 函数
import { useNavigate } from 'react-router-dom'; // 导入 useNavigate

const FavoriteList = () => {
  const navigate = useNavigate(); // 初始化 navigate
  const [favorites, setFavorites] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [selectedIds, setSelectedIds] = useState([]); // 存储选中的图片ID
  const [isBatchDeleteMode, setIsBatchDeleteMode] = useState(false);

  const userId = getUserId(); // 获取 user_id

  // 检查 userId 是否存在
  if (!userId) {
    navigate('/login'); // 如果不存在，重定向到登录页面
    return null; // 退出组件渲染
  }

  // 获取收藏列表
  const fetchFavorites = async (page) => {
    setLoading(true);
    try {
      const response = await axios.get(
        `${endpoints.joinFavoritelist}?sort=-created&page=${page}&perPage=12&filter=user_id.id='${userId}'&expand=users`
      );
      setFavorites(response.data.items);
      setTotalPages(response.data.totalPages);
    } catch (error) {
      console.error("获取收藏失败:", error);
      Toast.show({ content: '加载失败', position: 'center' });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchFavorites(currentPage);
  }, [currentPage]);

  // 单机选中/取消选中
  const handleSingleClick = (id) => {
    if (!isBatchDeleteMode) return;
    setSelectedIds((prev) => 
      prev.includes(id) 
        ? prev.filter(item => item !== id) 
        : [...prev, id]
    );
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedIds.length === 0) {
      Toast.show({ content: '请先选择要删除的图片', position: 'center' });
      return;
    }
    
    // 批量触发删除请求，不等待返回
    selectedIds.forEach(id => {
      axios.delete(`${endpoints.deleteFavoriteOne}/${id}`).catch(error => {
        console.error(`删除ID ${id} 失败:`, error);
      });
    });
    
    // 直接更新状态
    setFavorites(prev => prev.filter(item => !selectedIds.includes(item.id)));
    setSelectedIds([]);
    setIsBatchDeleteMode(false);
    Toast.show({ content: '删除操作已执行', position: 'center' });
  };

  return (
    <div className="mobile-scroll">
      <div style={{ padding: '10px', minHeight: '100%' }}>
        <button onClick={() => navigate(-1)} style={{ position: 'absolute', left: 12, top: 10, background: 'none', border: 'none', color: '#1677ff', fontSize: 16, cursor: 'pointer' }}>←</button>
        <h1 style={{ fontSize: '18px', textAlign: 'center', marginBottom: '10px' }}>
          通感收藏列表
        </h1>
       
        
        {loading ? (
          <p style={{ textAlign: 'center' }}>加载中...</p>
        ) : (
          <div 
            style={{ 
              display: 'grid', 
              gridTemplateColumns: 'repeat(3, 1fr)', 
              gap: '10px',
              marginBottom: '15px'
            }}
          >
            {favorites.map((item, index) => (
              <Card
                key={item.id}
                onClick={() => handleSingleClick(item.id)}
                style={{
                  padding: '5px',
                  border: selectedIds.includes(item.id) && isBatchDeleteMode 
                    ? '2px solid #1677ff' 
                    : '1px solid #eee',
                  borderRadius: '8px',
                  background: selectedIds.includes(item.id) && isBatchDeleteMode 
                    ? '#e6f7ff' 
                    : 'white',
                  transition: 'all 0.2s'
                }}
              >
                <ModalImage
                  small={item.pic}
                  large={item.pic}
                  alt={item.collectionName}
                  style={{ 
                    width: '100%', 
                    aspectRatio: '1/1', // 保持正方形比例
                    objectFit: 'cover', // 图片自适应
                    borderRadius: '4px'
                  }} 
                />
              </Card>
            ))}
          </div>
        )}

        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          marginTop: '15px',
          flexWrap: 'wrap',
          gap: '10px',
          paddingBottom: '10px'
        }}>
          {/* <Button 
            onClick={() => setIsBatchDeleteMode(!isBatchDeleteMode)}
            color={isBatchDeleteMode ? 'warning' : 'primary'}
            size="small"
          >
            {isBatchDeleteMode ? '取消批量删除' : '批量删除'}
          </Button> */}
          <div style={{ display: 'flex', gap: '10px' }}>
            <Button 
              disabled={currentPage <= 1} 
              onClick={() => setCurrentPage(currentPage - 1)}
              size="small"
            >
              上页
            </Button>
            <Button 
              disabled={currentPage >= totalPages} 
              onClick={() => setCurrentPage(currentPage + 1)}
              size="small"
            >
              下页
            </Button>
          </div>
          {/* {isBatchDeleteMode && (
            <Button 
              onClick={handleBatchDelete}
              color="danger"
              size="small"
            >
              确认删除
            </Button>
          )} */}
        </div>
      </div>
    </div>
  );
};

export default FavoriteList;